// useUpload.js
import { ref } from 'vue';
import { handleFiles } from './utils';

export const useUpload = (props, emit, UPLOAD_URL) => {
    const isDragging = ref(false);
    const uploading = ref(false);
    const uploadProgress = ref({});

    const triggerUpload = () => {
        if (props.modelValue.length >= props.maxCount) {
            emit('error', `最多上传 ${props.maxCount} 个文件`);
            return;
        }

        // #ifdef H5
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = props.accept;
        input.multiple = true;
        input.onchange = (e) => handleFiles(e.target.files, props.modelValue, props.maxCount, emit, uploadProgress, UPLOAD_URL);
        input.click();
        // #endif


        // #ifdef APP-PLUS
        uni.chooseImage({
            count: props.maxCount - props.modelValue.length,
            sourceType: ['album', 'camera'],
            success: (res) => {
                uploadFiles(res.tempFilePaths);
            },
            fail: (err) => {
                console.error('选择图片失败:', err);
                emit('error', '选择文件失败');
            }
        });
        // #endif
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        isDragging.value = true;
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
        isDragging.value = false;
    };

    const handleDrop = async (e) => {
        e.preventDefault();
        e.stopPropagation();
        isDragging.value = false;

        if (!e.dataTransfer) {
            emit('error', '无效的拖拽操作');
            return;
        }

        const files = Array.from(e.dataTransfer.files || []);
        if (files.length === 0) {
            emit('error', '未检测到有效文件');
            return;
        }

        const remaining = props.maxCount - props.modelValue.length;
        if (remaining <= 0) {
            emit('error', `最多上传 ${props.maxCount} 个文件`);
            return;
        }

        await handleFiles(files.slice(0, remaining), props.modelValue, props.maxCount, emit, uploadProgress, UPLOAD_URL);
    };

    return {
        isDragging,
        uploading,
        uploadProgress,
        triggerUpload,
        handleDragOver,
        handleDragLeave,
        handleDrop
    };
};